var editFlowId = "0";
var isEdit = false;
var seletFlowId = "0";
var curSelFlowId = "0";


var layerIndex;
var layerInitWidth;
var layerInitHeight;
/**
 * flow对象
 * */
var FlowObj = {
    buildParam:function (flowId,flowName,sortNum,flowJsonStr) {
        var flowObj = {};
        flowObj.flowId = flowId;
        flowObj.flowName = flowName;
        flowObj.sortNum = sortNum;
        flowObj.flowJsonStr = flowJsonStr;//用于暂存当前页面的步骤设置
        return flowObj;
    }
};
var existsFlowObjs = [];//已存在的flows 集合
if(existsFlows!=null && existsFlows!=undefined && existsFlows.length>0){
    $.each(existsFlows,function () {
        existsFlowObjs.push(FlowObj.buildParam(this.id,this.flowName,this.sortNum,this.flowJsonStr));
    });
}



layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        layer=layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    //添加流程
    function addFlow(edit,id){
        console.log("flowType:"+flowType);
        var params = "?packageId="+packageId+"&flowType="+flowType+"&flowId="+id;
        currentIndex = layer.open({
            title : "新增流程",
            type : 2,
            content : [baseUrl+"/flowConfig/addSpeakingFlow"+params],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['350px','230px'],
            success: function(layero, index) {
                //获取当前弹出窗口的索引及初始大小
                layerIndex      = index;
                layerInitWidth  = $("#layui-layer"+layerIndex).width();
                layerInitHeight = $("#layui-layer"+layerIndex).height();
                resizeLayer(layerIndex,layerInitWidth,layerInitHeight);
            },
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
        });
    }
    $("#add_flow").click(function(){
        addFlow(isEdit,editFlowId);
        //还原初始值
        editFlowId = 0;
        isEdit = false;
    });


    $("#setFlowSort").click(function(){
        var params = "?packageId="+packageId+"&flowType="+flowType;
        currentIndex = layer.open({
            title : "设置流程节点顺序",
            type : 2,
            content : [baseUrl+"/flowConfig/setFlowSort"+params],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['50%','55%'],
            success: function(layero, index) {
                //获取当前弹出窗口的索引及初始大小
                layerIndex      = index;
                layerInitWidth  = $("#layui-layer"+layerIndex).width();
                layerInitHeight = $("#layui-layer"+layerIndex).height();
                resizeLayer(layerIndex,layerInitWidth,layerInitHeight);
            },
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
        });
    });

    //流程节点
    $("#add_flow_step_c").click(function () {
        saveOrUpateFlowStep(false,"0","c");
    });
    $("#add_flow_step_s").click(function () {
        if(flowType=='multiWheel'){
            saveOrUpateFlowStep(false,"0","m");
        }else{
            saveOrUpateFlowStep(false,"0","s");
        }
    });

    //编辑流程节点
    function saveOrUpateFlowStep(edit,id,type) {
        if(seletFlowId == "0"){
            layer.msg("请选择流程，再进行添加节点操作");
            return;
        }
        var params = "?stepId="+id+"&flowId="+seletFlowId+"&type="+type+"&packageId="+packageId;
        var width = "65%";
        var higth = "85%";
        if(type != "c"){
            width = "65%";
            higth = "85%";
        }
        var currentIndex = window.parent.layer.open({
            title : "新增流程节点",
            type : 2,
            content : [baseUrl+"/flowConfig/saveOrUpdateSpeakingFlowStep"+params],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : [width,higth],
            success: function(layero, index) {
                //获取当前弹出窗口的索引及初始大小
                layerIndex      = index;
                layerInitWidth  = $("#layui-layer"+layerIndex).width();
                layerInitHeight = $("#layui-layer"+layerIndex).height();
                resizeLayer(layerIndex,layerInitWidth,layerInitHeight);
            },
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = window.parent.layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
                // localStorage
            }
            , btn2: function (index, layero) {
                window.parent.layer.close(index);
            }
        });
        setTimeout(function(){
            window.parent.layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                tips: 3
            });
        },500);
        window.parent.layer.full(currentIndex);
        /*setTimeout(function(){
            layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                tips: 3
            });
        },500);
        layui.layer.full(currentIndex);*/
    }


    $(document).on('click','.flowMenu .editFlow',function(){
        $('.flowMenu').css({'display':'none'});
        if(currentFlow){
            var $currentFlow = $(currentFlow);
            var currentId = $currentFlow.attr('class');
            console.log(currentId);
            addFlow(true,$(currentFlow).attr('id'));
        }
    });

});

var currentFlow; //当前操作的流程
$('#leftDiv').on('contextmenu',function (e) {
    e=e||event;
    target = e.target||e.srcElement;
    currentFlow = target;
    if($(target).attr("class")=="flowDiv"){
        var $menu = $('.flowMenu');
        $('.todoMenu').css({'display':'none'});
        $menu.css({"display":'block','position':'fixed','zIndex':'10000'});
        $menu.css({'left':e.clientX,'top':e.clientY});
        return false;
    }else {
        return false;
    }
});


$(document).on('click','.flowMenu .deleteFlow',function(){
    if(currentFlow){
        var $currentFlow = $(currentFlow);
        var currentId = $currentFlow.attr('id');
        console.log(currentId);
        layer.confirm('您确定删除此流程？',{icon:3, title:'提示信息'},function(index){
            var load = window.parent.layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
            $.ajax({
                type: "POST",
                url:  baseUrl+'/flowConfig/delSpeakingFlow?flowId='+currentId,
                dataType: 'json',
                success: function (data) {
                    window.parent.layer.close(load);
                    if(data.code<=0){
                        layer.msg(data.msg);
                        layer.close(index);
                    }else{
                        $(currentFlow).remove();//移除该流程
                        layer.close(index);
                    }
                },
                error: function () {
                    window.parent.layer.close(load);
                    layer.msg("操作失败");
                    layer.close(index);
                }
            });
        });

    }
    $('.flowMenu').css({'display':'none'});
});




$('#leftDiv').on('click',function(e){
    $('.todoMenu').css({'display':'none'})
});



$(document).on('click','.flowMenu .setflow',function(e){
    if(currentFlow){
        var $currentFlow = $(currentFlow);
        var currentId = $currentFlow.attr('id');
        if(currentId){
            isEdit = true;
            editFlowId = currentId;
            $("#add_flow").click();
        }
    }
});


function addFlowDiv(id,parameter) {
    console.log(id);
    console.log($("#"+id).length);
    if($("#"+id).length>0){
       // $("#"+id).html(flowName);
        $.each(existsFlowObjs,function (index,obj) {
            if(obj.id == id){
                existsFlowObjs.splice(index,1); //删除下标为index的元素
                existsFlowObjs.push(FlowObj.buildParam(obj.id,obj.flowName,obj.sortNum,obj.flowJsonStr));
            }
        });
    }else{
        if(parameter!=null && parameter!=undefined){
            var paramObj = JSON.parse(parameter);
            existsFlowObjs.push(FlowObj.buildParam(paramObj.id,paramObj.flowName,paramObj.sortNum,paramObj.flowJsonStr));
        }
    }
    referFlows();
}

function loadFlowDiv(id) {
    curSelFlowId = id;
    $("#exportCurFlow").click();
   /* if(seletFlowId!="0" && seletFlowId != id){//判断为切换流程情况下 ===》保存当前的流程，再进行切换操作
        $("#exportCurFlow").click();
    }else{
        //根据传递过来的的id 加载新的流程节点数据
        $.each($(".flowDiv"),function () {
            if($(this).attr("id") == curSelFlowId){
                $(this).css("border-color","#E2184D");
            }else{
                $(this).css("border-color","#0A7BFA");
            }
        });
        //暂存当前的===窗体
        $("#reset").click();
    }*/
}

function loadFlow(data) {
    currentObj = data;
    if(data.packageId == packageId && data.flowId == curSelFlowId ){
        if(data.type == "c"){
            $("#add_nomal").click();
        }else{
            $("#add_redirect").click();
        }
    }
}

function saveFlow() {
    //弹出loading
    var load = window.parent.layer.msg('流程数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
    saveDate(load);
}

/**
 * 保存当前流程
 * blocksStr 节点的jsonStr
 * connectPointsStr  节点的连接点jsonStr
 * connectRelationStr 节点的连接关系
 * */
function saveDate(load){
    if(skipStepStr==""||commonStepStr==""|| connectPointsStr==""||connectRelationStr==""){
        window.parent.layer.close(load);
        layer.msg("当前流程数据结构不完整");
    }else{
        var m = {
            typeSkip:skipStepStr,
            typeCommon:commonStepStr
        };
        var params = "?stepMap="+m+"&connectPointsStr="+connectPointsStr+"connectRelationStr"+connectRelationStr;

        var submitData = {};
        submitData["typeSkip"] = skipStepStr;
        submitData["typeCommon"] = commonStepStr;
        submitData["connectPointsStr"] = connectPointsStr;
        submitData["connectRelationStr"] = connectRelationStr;
        $.ajax({
            type: "POST",
            url:  baseUrl+'/flowConfig/saveFlow',
            data: submitData,
            dataType: 'json',
            async: false,
            success: function (data) {
                console.log(data);
                window.parent.layer.close(load);
                if(data.code<=0){
                    layer.msg(data.msg);
                }else{
                    layer.msg("保存成功");
                    //保存成功后更新flow
                    /*var jsonData = {};//重新构建
                    jsonData["typeSkip"] = skipStepStr;
                    jsonData["typeCommon"] = commonStepStr;
                    jsonData["connectPointsStr"] = connectPointsStr;
                    jsonData["connectRelationStr"] = connectRelationStr;
                    jsonStr = JSON.stringify(jsonData);
                    */

                    if(data.records!=null && data.records.length>0){
                        console.log(data.records[0].flowJsonStr);
                        $("#"+seletFlowId).attr("value",data.records[0].flowJsonStr);
                    }

                    //关闭本窗体
                    setTimeout(function () {
                        $("#cancel").click();
                    },1000);
                }
            },
            error: function () {
                window.parent.layer.close(load);
                layer.msg("保存失败");
                return ;
            }
        });
    }
}

/**
 * 修改节点
 * */
function editNode(currentId,obj) {
    if(obj.packageId == undefined || obj.packageId==null){
        obj.packageId = packageId;
    }
    var paramStr = "stepId="+currentId+"&type="+obj.type+"&flowStepVo="+encodeURIComponent(JSON.stringify(obj));
    var width = "50%";
    var higth = "89%";
    if(obj.type != "c"){
        width = "50%";
        higth = "83%";
    }
    var editWin = window.parent.layer.open({
        title : "编辑流程节点",
        type : 2,
        content : [baseUrl+"/flowConfig/saveOrUpdateSpeakingFlowStepById?"+paramStr],
        resize:true,
        maxmin:false,
        isOutAnim:true,
        scrollbar:true,
        area : [width,higth],
        success: function(layero, index) {
            //获取当前弹出窗口的索引及初始大小
            layerIndex      = index;
            layerInitWidth  = $("#layui-layer"+layerIndex).width();
            layerInitHeight = $("#layui-layer"+layerIndex).height();
            resizeLayer(layerIndex,layerInitWidth,layerInitHeight);
        },
        btn: ['保存', '取消'],
        yes: function (index, layero) {
            var body = window.parent.layer.getChildFrame('body', index); //得到子页面层的BODY
            var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
            button.click();
        }
        , btn2: function (index, layero) {
            window.parent.layer.close(index);
        }
    });
    setTimeout(function(){
        window.parent.layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
            tips: 3
        });
    },500);
    window.parent.layer.full(editWin);
}


/**
 * 刷新flow数据信息
 * */
function referFlows() {
    var params = "packageId="+packageId+"&flowType="+flowType;
    $('#flowDivs').load(baseUrl+'/flowConfig/getFlowBypackageId?'+params);
}


function resizeLayer(layerIndex,layerInitWidth,layerInitHeight) {
    var docWidth = $(document).width();
    var docHeight = $(document).height();
    var minWidth = layerInitWidth > docWidth ? docWidth : layerInitWidth;
    var minHeight = layerInitHeight > docHeight ? docHeight : layerInitHeight;
    console.log("doc:",docWidth,docHeight);
    console.log("lay:",layerInitWidth,layerInitHeight);
    console.log("min:",minWidth,minHeight);
    layer.style(layerIndex, {
        width: minWidth,
        height:minHeight
    });
}


//用于窗体通讯是否 刷新更新 窗体流程信息
window.addEventListener("storage", function(event) {
    switch (event.key) {
        case "changeDataVal":
            var dataVal = event.newValue;
            if(dataVal!=""){
                loadFlow(JSON.parse(dataVal));
            }
            break;
    }
});
